package sensors;

import java.awt.Container;

import javax.swing.JFrame;

import src.Logger;
import zcSensor.ZCSensor;

public class EmulatedSensor implements ISensor{
	
	private Logger logger;
	private EmulatedRunnable r;
	private double[] range;
	private int type = 0;
	private boolean online = true;
	private boolean AscDesc = true;
	
	/**
	 * Costruttore di default del sensore emulato. 
	 * 
	 * @param range valori di range che deve includere minimo, valore di soglia, valore di massimo
	 * @param type
	 */
	public EmulatedSensor(double[] range, int type, boolean AscDesc){
		logger = Logger.getLogger();
		this.type = type;
		this.AscDesc = AscDesc;
		
		if(range.length!=3){
			logger.write(EmulatedSensor.class.getSimpleName(),"Dimensionamento intervallo errato: "+range.length);
			online = false;
		}else				{
		this.range = range;
		online = true;
		}
		
		
		
		r = new EmulatedRunnable(); 
		Thread t = new Thread(r);
		t.start();
	}

	@Override
	public double getValue() {
		if((r.getValue()<range[0])||(r.getValue()>range[2])){
			if(this.online)
			logger.write(EmulatedSensor.class.getSimpleName(),"Valore fuori range: "+r.getValue());
			this.online = false;
		}else
			this.online = true;
		
		return r.getValue();
	}

	@Override
	public double[] getRange() {
		return range;
	}

	@Override
	public Object[] getData() {
		return null;
	}

	@Override
	public int getType() {
		return type;
	}
	
	@Override
	public void setRange(double min, double thresh, double max) {
		if((min<thresh)&&(thresh<max)){
		range = new double[]{min,thresh,max};
		online = true;
		return;
		}else{
			if((thresh<min)||(thresh>max)){
				logger.write(EmulatedSensor.class.getSimpleName(), "Soglia non accettata: "+min+":"+thresh+":"+max);
				this.online = false;
				return;
			}
			double tmpA = Math.min(min,max);
			double tmpB = Math.max(min, max);
			range = new double[]{tmpA,thresh,tmpB};
			this.online = true;
		}
		
	}
	@Override
	public boolean getOnline() {
		return online;
	}

	@Override
	public boolean getASCDESC() {
		return AscDesc;
	}

}

class EmulatedRunnable implements Runnable{
	ZCSensor sensore;
	
	public EmulatedRunnable() {
		sensore = new ZCSensor();
		JFrame frame = new JFrame("Sensor Emulator");
		Container thePane = frame.getContentPane();

		thePane.add(sensore);
		
		frame.pack();
		frame.setVisible(true);

	}
	
	@Override
	public void run() {
	}
	
	double getValue(){
		return (sensore.getAngle()+3.14)/6.28;
	}
}

